package com.example.auth.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.example.auth.common.R;
import com.example.auth.model.entity.SysDepartment;
import com.example.auth.model.vo.DepartmentTreeVo;
import com.example.auth.service.SysDepartmentService;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;

/**
 * 部门管理控制器
 */
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Resource
    private SysDepartmentService departmentService;

    /**
     * 获取部门树形结构
     */
    @GetMapping("/tree")
    public R<List<DepartmentTreeVo>> getDepartmentTree() {
        List<DepartmentTreeVo> tree = departmentService.getDepartmentTree();
        return R.ok(tree);
    }

    /**
     * 获取部门详情
     */
    @GetMapping("/{id}")
    public R<SysDepartment> getDepartmentById(@PathVariable Long id) {
        SysDepartment department = departmentService.getById(id);
        return R.ok(department);
    }

    /**
     * 添加部门
     */
    @PostMapping
    @SaCheckPermission("department:add")
    public R<Boolean> addDepartment(@RequestBody SysDepartment department) {
        boolean result = departmentService.save(department);
        return R.ok(result);
    }

    /**
     * 更新部门
     */
    @PutMapping
    @SaCheckPermission("department:update")
    public R<Boolean> updateDepartment(@RequestBody SysDepartment department) {
        boolean result = departmentService.updateById(department);
        return R.ok(result);
    }

    /**
     * 删除部门
     */
    @DeleteMapping("/{id}")
    @SaCheckPermission("department:delete")
    public R<Boolean> deleteDepartment(@PathVariable Long id) {
        // 检查是否有子部门
        List<SysDepartment> children = departmentService.getDepartmentWithChildren(id);
        if (children.size() > 1) {
            return R.failed("该部门下存在子部门，无法删除");
        }
        boolean result = departmentService.removeById(id);
        return R.ok(result);
    }
} 